<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
<script>

    // async 函数  => 异步函数  => 可以让异步操作变得更加方便(更像同步  -> 异步操作需要用Promise封装)



    function getNumAsync(num, delay = 0, isFulfilled = true) {
        return new Promise(function (resolve, reject) {
            setTimeout(() => {
                isFulfilled ? resolve(num) : reject(num);
            }, delay)
        })
    }

    // async function fn(){
    //     // 同时启动三个异步操作  => 按顺序返回结果
    //     var p1 = await getNumAsync(1, 2000, false);  // p1 Promise实例(pending) 2s后 变为 fulfilled
    //     console.log(p1);
    //     var p2 = await getNumAsync(2, 1000, true);  // p2 Promise实例(pending) 1s后 变为 fulfilled
    //     console.log(p2);
    //     var p3 = await getNumAsync(3, 3000, true);  // p3 Promise实例(pending) 3s后 变为 fulfilled
    //     console.log(p3);

    //     return p1+p2+p3;
    //     // console.log(p1,p2,p3);
    // }

    // var p = fn();
    // console.log("p",p);

    // p.then(v => {
    //     console.log("fulfilled", v); // 3
    // }).catch(err => {
    //     console.log("rejected", err);
    // })


    async function fn(){
        // 同时启动三个异步操作  => 按顺序返回结果
        try{
            var p1 = await getNumAsync(1, 2000, false);  // p1 Promise实例(pending) 2s后 变为 fulfilled
            console.log(p1);
            var p2 = await getNumAsync(2, 1000, true);  // p2 Promise实例(pending) 1s后 变为 fulfilled
            console.log(p2);
            var p3 = await getNumAsync(3, 3000, true);  // p3 Promise实例(pending) 3s后 变为 fulfilled
            console.log(p3);

            return p1+p2+p3;
        }catch(err){
            console.log("err",err);
        }
        // console.log(p1,p2,p3);
    }
    
    fn();
    
</script>
</html>